package org.dromara.tearoom.config;


import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.util.Timeout;
import org.dromara.tearoom.util.RestLogUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        // 1. 创建连接池管理器
        PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
        pool.setMaxTotal(200);          // 最大连接数
        pool.setDefaultMaxPerRoute(50); // 每个路由（域名）的并发上限

        // 2. 配置超时参数（单位：毫秒 → 转换为 Timeout）
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(Timeout.ofMilliseconds(5000))     // 连接建立超时
                .setConnectionRequestTimeout(Timeout.ofMilliseconds(5000)) // 从连接池获取连接的超时
                .setResponseTimeout(Timeout.ofMilliseconds(10000))    // 数据传输超时（原 SocketTimeout）
                .build();




        // 3. 创建带连接池和超时配置的 HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(pool)
                .setDefaultRequestConfig(requestConfig)
                .build();

        // 4.启用缓冲工厂（支持重复读取请求体/响应体）
        HttpComponentsClientHttpRequestFactory factory =
                new HttpComponentsClientHttpRequestFactory(httpClient);
        BufferingClientHttpRequestFactory bufferingFactory =
                new BufferingClientHttpRequestFactory(factory);

        // 5. 创建 RestTemplate 并添加日志拦截器
        RestTemplate restTemplate = new RestTemplate(bufferingFactory);
        restTemplate.getInterceptors().add(new RestLogUtil()); // 确保 RestLogUtil 能处理缓冲流

        return restTemplate;
    }
}
